﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using SPCFMedicineInformer.Constants;
using Vega.USiteBuilder;
using SPCFMedicineInformer.DocumentTypes;
using umbraco.NodeFactory;
using umbraco;

namespace SPCFMedicineInformer.Helpers
{
    public static class FormHelper
    {
        public static void BindDropDown(DropDownList ddl, DataTable dt, string textField, string valueField)
        {
            ddl.DataSource = dt;
            ddl.DataTextField = textField;
            ddl.DataValueField = valueField;
            ddl.DataBind();
        }
        public static void ShowMessage(MessageType type, string msg, Literal lit)
        {
            string sType = string.Empty;
            switch (type)
            {
                case MessageType.Done:
                    sType = "msg done";
                    break;
                case MessageType.Error:
                    sType = "msg error";
                    break;
                case MessageType.Warning:
                    sType = "msg warning";
                    break;
                default:
                    break;
            }
            var sb = new StringBuilder();
            var msgFormat = "<p class=\"{0}\">{1}</p>";
            sb.AppendLine(string.Format(msgFormat, sType, msg));
            lit.Visible = true;
            lit.Text = sb.ToString();
        }
        public static void ShowChildItemsOfCategory(Literal litSubCategoies, Literal litGenName, Literal litMedicine, Literal litSymptom, int catId,bool isTruncate = true)
        {
            int charCount = 50;
            var genNameList = ContentHelper.GetByNodeId(catId).GetChildren<MedicineGenericName>().OrderBy(node => node.Name);
            var sympcont = ContentHelper.GetByNodeId(catId).GetChildren<SymptomListing>().FirstOrDefault();
            var subCategories = ContentHelper.GetByNodeId(catId).GetChildren<MedicineCategory>().OrderBy(node=>node.Name);
            var sympList = sympcont != null ? sympcont.GetChildren<Symptom>().OrderBy(node => node.Name) : null;

            var sbGenList = new StringBuilder();
            var sbMedList = new StringBuilder();
            var sbSympList = new StringBuilder();
            var sbSubCatList = new StringBuilder();
            string result = string.Empty;

            foreach (var cat in subCategories)
            {   
                sbSubCatList.AppendLine(ParseIdToNameWithLink(cat.Id.ToString(),cat.Name, "/admin/utilities/medicine-categories/category-entry/"));
            }
            foreach (var gen in genNameList)
            {
                sbGenList.AppendLine(ParseIdToNameWithLink(gen.Id.ToString(), gen.Name, "/admin/utilities/medicine-generic-name/generic-name-entry"));
                foreach (var med in gen.GetChildren<MedicineItem>())
                {
                    string link = ParseIdToNameWithLink(med.Id.ToString(), med.Name, "/admin/utilities/medicine-entry");
                    sbMedList.AppendLine(link);
                }
            }
            if (sympList != null)
            {
                foreach (var symp in sympList)
                {
                    sbSympList.AppendLine(ParseIdToNameWithLink(symp.Id.ToString(), symp.Name, "/admin/utilities/symptoms-listing/symptom-entry"));
                }
            }
            
            result = sbSubCatList.ToString();
            litSubCategoies.Text = isTruncate ? StringUtils.TruncateIfLonger(result, charCount) : result;
            result = sbGenList.ToString();
            litGenName.Text = isTruncate ? StringUtils.TruncateIfLonger(result,charCount) : result;
            result = sbMedList.ToString();
            litMedicine.Text = isTruncate ? StringUtils.TruncateIfLonger(result, charCount) : result;
            result = sbSympList.ToString();
            litSymptom.Text = isTruncate ? StringUtils.TruncateIfLonger(result,charCount) : result;
        }
        public static string ShowChildItemsOfGenericName(int genId, bool isTruncate = true)
        {
            int charCount = 50;
            var sb = new StringBuilder();
            var medList = ContentHelper.GetByNodeId<MedicineGenericName>(genId).GetChildren<MedicineItem>();
            foreach (var med in medList)
            {
                sb.AppendLine(med.MedicineName + ",");
            }
            string result = sb.ToString();
            return isTruncate ? StringUtils.TruncateIfLonger(StringUtils.RemoveLastSymbol(result, ","), charCount) : StringUtils.RemoveLastSymbol(result, ",");
        }
        public static string ParseIdStringToNodeName(string strId,string delimeter)
        {
            var list = strId.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
            StringBuilder sb = new StringBuilder();
            foreach(var sid in list)
            {
                int tempInt;
                int id = int.TryParse(sid, out tempInt) ? tempInt : 0;
                if (id != 0)
                {
                    Node node = new Node(id);
                    if (node != null)
                    {
                        sb.AppendLine(node.Name + delimeter);
                    }
                }
            }

            return StringUtils.RemoveLastSymbol(sb.ToString(), delimeter);
        }
        public static string ParseIdStringToNodeName(string strId)
        {
            if (string.IsNullOrEmpty(strId)) return "";
            int id;
            if (!int.TryParse(strId, out id)) return "";
            Node node = new Node(id);
            if (node == null || string.IsNullOrEmpty(node.Name)) return "";
            return node.Name;
        }
        public static string ParseIdToNameWithLink(string strId,string strNames,string link)
        {
            var sb = new StringBuilder();
            var formatWithLink = "<span class=\"roundBorder\" title=\"Click on this item to edit or view its detail.\"><a href=\"" + link + "?id={0}\">{1}</a></span>";
            var formatNoLink = "<span class=\"roundBorder defaultCursor\" title=\"This item does not exist anymore.\">{0}</span>";
            var list = strId.Split(new string[] {","}, StringSplitOptions.RemoveEmptyEntries).ToList();
            var listName = strNames.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
            int ctr = 0;
            foreach (var sid in list)
            {
                int tempInt;
                int id = int.TryParse(sid,out tempInt) ? tempInt : 0;
                Node node = new Node(id);
                if (node != null && !string.IsNullOrEmpty(node.Name))
                {
                    sb.AppendLine(string.Format(formatWithLink, node.Id.ToString(), node.Name));
                }
                else if (listName.Count() > 0)
                {
                    sb.AppendLine(string.Format(formatNoLink,listName[ctr]));
                }
                ctr++;
            }
            return sb.ToString();
        }
        public static string GetDescendantsTotal(int startNodeId, string nodeTypeAlias)
        {
            Node Index = new Node(startNodeId);
            int levelRequirement = Index.Level + 2;
            if (Index != null && !string.IsNullOrEmpty(Index.Name))
            {   
                return Index.GetDescendantNodesByType(nodeTypeAlias).Where(node=>node.Level == levelRequirement).Count().ToString();
            }
            return "0";
        }
        public static string GetChildrenTotal(int startNodeId, string nodeTypeAlias)
        {
            Node Index = new Node(startNodeId);
            if (Index != null && !string.IsNullOrEmpty(Index.Name))
            {
                return Index.GetChildNodesByType(nodeTypeAlias).Count().ToString();
            }
            return "0";
        }
        public static string ParseNameToId(string strList)
        {
            var list = strList.ToLower().Split(new string[] {","},StringSplitOptions.RemoveEmptyEntries).Select(a=>a.TrimStart());
            var nodeList = NodeLocator.GetNodesOfExactType<MedicineItem>().Where(node => list.Contains(node.Name.ToLower())).Select(node=>node.Id.ToString());
            var result = string.Join(",", nodeList);
            return result;
        }
        public static int GetAge(string strBirthDate)
        {
            return GetAge(DateTime.Parse(strBirthDate));
        }
        public static int GetAge(DateTime birthDate)
        {
            DateTime today = DateTime.Now;
            int age = today.Year - birthDate.Year;
            if (birthDate > today.AddYears(-age)) age--;

            return age;
        }
    }
}
